package com.me.iot.server.socket;

import com.me.iot.domain.MeIOTSocketConfigInfo;

import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author mingke
 * @desc 接受下位机Socket连接的回调函数
 * @time 2022/5/10
 */
public class MeIOTAcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> {
    //存储TCP连接相关配置信息的配置类
    private MeIOTSocketConfigInfo configInfo;

    public MeIOTAcceptHandler(MeIOTSocketConfigInfo configInfo) {
        this.configInfo = configInfo;
    }

    @Override
    public void completed(AsynchronousSocketChannel socketChannel, AsynchronousServerSocketChannel serverSocketChannel) {
        try {
            //设置TCP的参数，作用目前为止不知道
            socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
            socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, configInfo.getSocketBufferSize());
            socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, configInfo.getSocketBufferSize());
            //设置读取数据的回调
            if(socketChannel.isOpen()) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(configInfo.getSocketBufferSize());
                byteBuffer.clear();
                socketChannel.read(byteBuffer, byteBuffer, new MeIOTReadHandler(socketChannel));
            }
            //连接成功以后，发送一个指令激活下位机
            byte[] result = {(byte) 0xef, 0x77, 0x00};
            socketChannel.write(ByteBuffer.wrap(result), null, new MeIOTWriteHandler());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //让服务器继续接受其他请求
            serverSocketChannel.accept(serverSocketChannel, this);
        }
    }

    @Override
    public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {

    }
}
